﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(menuName = "PluggableAI/Actions/Attack")]
public class AttackAction : Action {

    public override void Act(StateController stateController)
    {
        Attack(stateController);
    }

    private void Attack(StateController controller)
    {
        RaycastHit hit;
        float lookRange = 10;
        //朝向为forword时，用x轴和y轴的数值代表视线平面的大小的一半
        //z轴大小取0避免了当两个tank贴紧的时候，BoxCast检测不到hit的问题
        Vector3 lookPlane = new Vector3(.4f, .4f, 0);

        //根据转向改变lookPlane
        //当转为横向之后，z和x对调，即lookPlane的z轴非0,x轴为0
        lookPlane = controller.eyes.rotation * lookPlane;

        Debug.DrawRay(controller.eyes.position + lookPlane, controller.eyes.forward * lookRange, Color.yellow);
        Debug.DrawRay(controller.eyes.position + new Vector3(-lookPlane.x, lookPlane.y, -lookPlane.z), controller.eyes.forward * lookRange, Color.yellow);

        if (Physics.BoxCast(controller.eyes.position,
            new Vector3(Mathf.Abs(lookPlane.x), Mathf.Abs(lookPlane.y), Mathf.Abs(lookPlane.z)),/* 旋转之后有可能为负数，这里要代表box size所以要转为正数 */
            controller.eyes.forward, out hit)
            && (hit.collider.CompareTag("Player") || hit.collider.CompareTag("Headquarters")))
        {
            controller.tankShooting.Fire();
        }else if(Physics.Raycast(controller.eyes.position, controller.eyes.forward, out hit, lookRange)
            && (hit.collider.CompareTag("Player") || hit.collider.CompareTag("Headquarters")))
        {
            controller.tankShooting.Fire();
        }

        //if (hit.collider!=null)
        //Debug.Log("hit collider="+hit.collider.gameObject.name);
    }
}
